package com.gvfish.service;

import java.util.List;

import net.sf.dozer.util.mapping.DozerBeanMapper;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import com.gvfish.core.DozerBeanMapperFactory;
import com.gvfish.core.Page;
import com.gvfish.dao.CategoryDao;
import com.gvfish.entity.Article;
import com.gvfish.entity.Category;
import com.gvfish.vo.CategoryVo;

@Service
@Transactional
public class CategoryManager {
	@Autowired
	private CategoryDao categoryDao;

	@Transactional
	public void save(Category category, Long parentId) {
//		EntityManager em = EMF.get().createEntityManager();
//		try {
//			if(parentId!=null){
//				Category parent = em.find(Category.class, parentId);
//				category.setDepth(parent.getDepth() + 1);
//				parent.setHasChild(true);
//			}else{
//				category.setDepth(1);
//			}
//			em.persist(category);
//			System.out.println(category);
//		} finally {
//			em.close();
//		}

		 if(parentId!=null){
		 Category parent =categoryDao.getById(parentId);
		 category.setDepth(parent.getDepth()+1);
		 category.setParentId(parent.getId());
		 }else{
		 category.setDepth(1);
		 }
		 categoryDao.save(category);
	}
	public void update(Category category){
		Assert.notNull(category);
		categoryDao.update(category,category.getId());
	}

	@Transactional(readOnly=true)
	public List<Category> findAll() {
		return categoryDao.findAll();
	}

	@Transactional
	public void del(Long id) {
		categoryDao.del(id);
	}
	
	public void delAllArt(Long id){
		categoryDao.delAllArt(id);
	}

	@Transactional(readOnly = true)
	public Category find(Long id) {
		return categoryDao.getById(id);
	}

	public CategoryVo findVo(Long id) {
		DozerBeanMapper dm = DozerBeanMapperFactory.getMapper();
		CategoryVo vo = new CategoryVo();
		dm.map(find(id), vo);
		return vo;
	}

}
